package com.shungen.realapigateway;

import com.shungen.realapigateway.model.entity.InterfaceInfo;
import com.shungen.realapigateway.service.InterfaceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * 真实接口访问网关服务
 * @author shungen
 * @date 2024年08月10日 11:52
 */
@Slf4j
@MapperScan("com.shungen.realapigateway.mapper")
@SpringBootApplication
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class);
    }


    /**
     * 构建动态路由
     * @param builder
     * @param interfaceInfoService
     * @return
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder, InterfaceInfoService interfaceInfoService) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.getAllInterface();
        for (InterfaceInfo interfaceInfo : interfaceInfoList) {
            routes.route("route_" + interfaceInfo.getId(),
                    r -> r.path("/openapi/**") // 匹配以 /openapi 开头的所有路径
                            .and()  // 添加额外的断言
                            .header("interfaceId", String.valueOf(interfaceInfo.getId()))  // 检查请求头中的 interfaceId 是否匹配
                            .filters(f -> f.stripPrefix(1))  // 使用现成的 StripPrefix 过滤器去掉 /openapi 前缀
                            .uri(interfaceInfo.getUrl())
            );
        }
        return routes.build();
    }






}
